package com.ptc.otkjavaexamples.ui;/*--------------------------------------------------------------------------*\
|
|  Module Details:
|
|  Name:    TechniqueViewController.java
|
|  Purpose: Display the TechniqueViewController dialog
\*--------------------------------------------------------------------------*/

import com.ptc.cipjava.intseq;
import com.ptc.cipjava.jxthrowable;
import com.ptc.cipjava.stringseq;
import com.ptc.otkjavaexamples.ui.pojo.DataPack;
import com.ptc.otkjavaexamples.ui.pojo.DataStorage;
import com.ptc.pfc.pfcAssembly.Assembly;
import com.ptc.pfc.pfcAssembly.ComponentPath;
import com.ptc.pfc.pfcAssembly.pfcAssembly;
import com.ptc.pfc.pfcCommand.DefaultUICommandActionListener;
import com.ptc.pfc.pfcModel.Model;
import com.ptc.pfc.pfcModelItem.ModelItemType;
import com.ptc.pfc.pfcSession.Session;
import com.ptc.uifc.uifcComponent.*;
import com.ptc.uifc.uifcCore.CheckState;
import com.ptc.uifc.uifcCore.ItemPositionData;
import com.ptc.uifc.uifcCore.uifcCore;
import com.ptc.uifc.uifcDialog.*;
import com.ptc.uifc.uifcInputPanel.*;
import com.ptc.uifc.uifcPushButton.*;
import com.ptc.uifc.uifcTree.*;
import com.ptc.wfc.wfcModelItem.WModelItem;
import com.ptc.wfc.wfcSolid.WSolid;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;


public class TechniqueViewController extends DefaultUICommandActionListener
{
  static {
    new ResourceParser();
  }
  private String techniqueviewcontroller_dialog = "TechniqueViewController";
  private String techniqueviewcontroller_inputpanel1 = "InputPanel1";
  private String techniqueviewcontroller_pushbutton1 = "PushButton1";
  private String techniqueviewcontroller_tree1 = "Tree1";
  private String techniqueviewcontroller_pushbutton2 = "PushButton2";
  private String techniqueviewcontroller_pushbutton3 = "PushButton3";


  public static Map<String, DataStorage> map = null;
  public static List<String> composeSequence = null;

  private static Session session;

  public static void testHideAndUnhide(int [] arr,boolean hide){
    try{
      if(arr ==null){
        return;
      }
      Model model = session.GetCurrentModel();
      Assembly assembly = (Assembly) model;

      if(model==null){
        return;
      }

      WModelItem modelItem ;

      int length = arr.length;

      if(length==1){
        modelItem =  (WModelItem) assembly.GetItemById(ModelItemType.ITEM_FEATURE, arr[0]);
      }else {

        intseq path = intseq.create();
        for (int i = 0; i < length-1; i++) {
          path.append(arr[i]);
        }
        //        path.append(43);
        ComponentPath componentPath = pfcAssembly.CreateComponentPath(assembly, path);
        //        Selection selection = pfcSelect.CreateComponentSelection(componentPath);
        //        selection.Display();
        WSolid solid = (WSolid) componentPath.GetLeaf();
        modelItem = (WModelItem) solid.GetItemById(ModelItemType.ITEM_FEATURE, arr[length-1]);
      }



      if(hide){
        modelItem.Hide();
      }else {
        modelItem.Unhide();
      }
    }catch (Exception e){
      System.err.println("控制显隐错误");
      e.printStackTrace();
    }

  }


  public TechniqueViewController(Session session) {
    TechniqueViewController.session = session;
  }

  // Windows路径正则表达式
  private static final Pattern WINDOWS_PATH_PATTERN = Pattern.compile(
          // 绝对路径: 如 C:\folder\file.txt 或 \\server\share\file.txt
          "^(?:[a-zA-Z]:\\\\|\\\\\\\\[^\\\\]+\\\\[^\\\\]+)(?:[^\\\\/:*?\"<>|]+\\\\?)*$|" +
                  // 相对路径: 如 folder\file.txt 或 .\file.txt 或 ..\file.txt
                  "^(?:\\.|\\.\\.|[^\\\\/:*?\"<>|]+)(?:\\\\[^\\\\/:*?\"<>|]+)*$"
  );

  /**
   * 使用正则表达式验证Windows路径
   */
  public static boolean isValidWindowsPathRegex(String path) {
    if (path == null || path.isEmpty()) {
      return false;
    }
    return WINDOWS_PATH_PATTERN.matcher(path).matches();
  }

  /**
   * 从Windows路径字符串中提取文件名
   *
   * @param windowsPath Windows路径字符串（如 "C:\folder\file.txt" 或 "\\server\share\document.pdf"）
   * @return 提取到的文件名，如果路径为空或无效则返回null
   */
  public static String extractFileName(String windowsPath) {
    // 检查输入是否为空
    if (windowsPath == null || windowsPath.trim().isEmpty()) {
      return null;
    }

    // 处理路径中的反斜杠（统一使用单个反斜杠处理）
    String path = windowsPath.replace("\\\\", "\\");

    // 找到最后一个反斜杠的位置
    int lastBackslashIndex = path.lastIndexOf('\\');

    // 如果没有反斜杠，说明整个路径就是文件名
    if (lastBackslashIndex == -1) {
      // 检查是否是类似 "C:file.txt" 这样的路径
      int colonIndex = path.indexOf(':');
      if (colonIndex != -1 && colonIndex < path.length() - 1) {
        return path.substring(colonIndex + 1);
      }
      return path;
    }

    // 从最后一个反斜杠后面开始截取，得到文件名
    String fileName = path.substring(lastBackslashIndex + 1);

    // 去掉后缀


    // 处理可能的空文件名（如路径以反斜杠结尾的情况）
    return fileName.isEmpty() ? null : fileName;
  }




  @Override
  public void OnCommand() throws jxthrowable {
    TechniqueViewController_main();

  }


  class TechniqueViewControllerDialogListener extends DefaultDialogListener
  {
    TechniqueViewControllerDialogListener() {}

    public void OnClose(Dialog handle)
    {
      try
      {
        uifcComponent.ExitDialog(techniqueviewcontroller_dialog, 0);
      }
      catch (Throwable e) {}
    }
  }


  class InputPanel1InputPanelListener extends DefaultInputPanelListener
  {
    InputPanel1InputPanelListener() {}

    public void OnActivate(InputPanel handle) {}
  }


  class PushButton1PushButtonListener extends DefaultPushButtonListener
  {
    PushButton1PushButtonListener() {}

    public void OnActivate(PushButton handle) {
      try {
        InputPanel inputPanel = uifcInputPanel.InputPanelFind(techniqueviewcontroller_dialog, techniqueviewcontroller_inputpanel1);
        String path = inputPanel.GetStringValue();
        if(!TechniqueViewController.isValidWindowsPathRegex(path)){

          System.err.println("文件路径不对");
          return;
        }

        String techniqueName = TechniqueViewController.extractFileName(path);

        ResourceParser resourceParser = new ResourceParser(path);
        DataPack dataPack = resourceParser.parseFile();
        TechniqueViewController.map = dataPack.getMap();
        TechniqueViewController.composeSequence = dataPack.getComposeSequence();

//        map.forEach((key,value) ->{
//          System.out.println(key + value.toString());
//        });

        Tree tree = uifcTree.TreeFind(techniqueviewcontroller_dialog, techniqueviewcontroller_tree1);

        composeTreeStructure(tree,map,techniqueName,composeSequence);

      } catch (jxthrowable e) {
        System.err.println("搜索不到资源路径输入框");
        e.printStackTrace();
      } catch (IOException e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
      }
    }

    //组装树结构
    private void composeTreeStructure(Tree handle, Map<String, DataStorage> map , String  techniqueName, List<String> composeSequence) throws jxthrowable {



        TreeItem root = uifcTree.TreeItemDefine("root");
        root.SetText(techniqueName);
        root.SetIsOpen(true);
        ItemPositionData position = uifcCore.ItemPositionData_Create();
        handle.InsertItem(root,position);

      for (int i = 0; i < composeSequence.size(); i++) {
        String id = composeSequence.get(i);
        DataStorage value = map.get(id);
        try {
          TreeItem item = uifcTree.TreeItemDefine(id);
          String label = value.getLabel();
          String parentId = value.getParentId();
          item.SetText(label);
          item.SetParentName(parentId);
//          System.out.println("label = "+label+" parentId = "+parentId);
          handle.InsertItem(item,position);
        } catch (jxthrowable e) {
          System.err.println("包装树节点错误");
          e.printStackTrace();
        }
      }


    }
  }


  class Tree1TreeListener extends DefaultTreeListener
  {
    Tree1TreeListener() {}

    public void OnItemSelect(Tree handle) {}
    public void OnItemActivate(Tree handle) {}
  }


  class PushButton2PushButtonListener extends DefaultPushButtonListener
  {


    PushButton2PushButtonListener() {
    }


    public void OnActivate(PushButton handle){
      Map<String, DataStorage> map = TechniqueViewController.map;
      if(map ==null){
        System.err.println("数据表是空的，没法切换显示");
        return;
      }
      if(composeSequence==null){
        System.err.println("id表是空的，没法遍历");
        return ;
      }
      for (int i = 0; i < composeSequence.size(); i++) {

        TreeItem item = null;
        try {
          item = uifcTree.TreeItemFind(techniqueviewcontroller_dialog, techniqueviewcontroller_tree1, composeSequence.get(i));
        } catch (jxthrowable e) {
          System.err.println("找不到节点");
          e.printStackTrace();
        }

        String itemName = null;
        try {
          itemName = item.GetName();
        } catch (jxthrowable e) {

          System.err.println("节点没名字");
        }

        CheckState checkState = null;
        try {
          checkState = item.GetCheckedState();
        } catch (jxthrowable e) {
          System.err.println("没被选中的节点难道根本没有这个属性"+e.getMessage()+"if so, it's stupid!");
        }
        if (checkState == null) {

          continue;
        }
        if(checkState.getValue()==CheckState.CHECK_STATE_SET.getValue()){

          DataStorage dataStorage = map.get(itemName);
          if(dataStorage.getPath()==null){
            continue;
          }
          TechniqueViewController.testHideAndUnhide(dataStorage.getPath(),false);
//          try {
//            System.out.println(item.GetText());
//          } catch (jxthrowable e) {
//            System.err.println("找不到节点名字");
//            e.printStackTrace();
//          }
        }
      }
    }
  }


  class PushButton3PushButtonListener extends DefaultPushButtonListener
  {
    PushButton3PushButtonListener() {}

    public void OnActivate(PushButton handle) {
      Map<String, DataStorage> map = TechniqueViewController.map;
      if(map ==null){
        System.err.println("数据表是空的，没法切换显示");
        return;
      }
      if(composeSequence==null){
        System.err.println("id表是空的，没法遍历");
        return ;
      }
      for (int i = 0; i < composeSequence.size(); i++) {

        TreeItem item = null;
        try {
          item = uifcTree.TreeItemFind(techniqueviewcontroller_dialog, techniqueviewcontroller_tree1, composeSequence.get(i));
        } catch (jxthrowable e) {
          System.err.println("找不到节点");
          e.printStackTrace();
        }

        String itemName = null;
        try {
          itemName = item.GetName();
        } catch (jxthrowable e) {

          System.err.println("节点没名字");
        }

        CheckState checkState = null;
        try {
          checkState = item.GetCheckedState();
        } catch (jxthrowable e) {
          System.err.println("没被选中的节点难道根本没有这个属性"+e.getMessage()+"if so, it's stupid!");
        }
        if (checkState == null) {

          continue;
        }
        if(checkState.getValue()==CheckState.CHECK_STATE_SET.getValue()){

          DataStorage dataStorage = map.get(itemName);
          if(dataStorage.getPath()==null){
            continue;
          }
          TechniqueViewController.testHideAndUnhide(dataStorage.getPath(),true);
//          try {
//            System.out.println(item.GetText());
//          } catch (jxthrowable e) {
//            System.err.println("找不到节点名字");
//            e.printStackTrace();
//          }
        }
      }
    }
  }





  public void TechniqueViewController_main()
  {
    try
    {
      uifcComponent.CreateDialog(techniqueviewcontroller_dialog, techniqueviewcontroller_dialog);

      Dialog techniqueviewcontroller = uifcDialog.DialogFind(techniqueviewcontroller_dialog, techniqueviewcontroller_dialog);
      TechniqueViewControllerDialogListener techniqueviewcontrollerLis = new TechniqueViewControllerDialogListener();
      techniqueviewcontroller.AddActionListener(techniqueviewcontrollerLis);

      InputPanel inputpanel1 = uifcInputPanel.InputPanelFind(techniqueviewcontroller_dialog, techniqueviewcontroller_inputpanel1);
      InputPanel1InputPanelListener inputpanel1Lis = new InputPanel1InputPanelListener();
      inputpanel1.AddActionListener(inputpanel1Lis);

      PushButton pushbutton1 = uifcPushButton.PushButtonFind(techniqueviewcontroller_dialog, techniqueviewcontroller_pushbutton1);
      PushButton1PushButtonListener pushbutton1Lis = new PushButton1PushButtonListener();
      pushbutton1.AddActionListener(pushbutton1Lis);

      Tree tree1 = uifcTree.TreeFind(techniqueviewcontroller_dialog, techniqueviewcontroller_tree1);
      Tree1TreeListener tree1Lis = new Tree1TreeListener();
      tree1.AddActionListener(tree1Lis);

      PushButton pushbutton2 = uifcPushButton.PushButtonFind(techniqueviewcontroller_dialog, techniqueviewcontroller_pushbutton2);
      PushButton2PushButtonListener pushbutton2Lis = new PushButton2PushButtonListener();
      pushbutton2.AddActionListener(pushbutton2Lis);

      PushButton pushbutton3 = uifcPushButton.PushButtonFind(techniqueviewcontroller_dialog, techniqueviewcontroller_pushbutton3);
      PushButton3PushButtonListener pushbutton3Lis = new PushButton3PushButtonListener();
      pushbutton3.AddActionListener(pushbutton3Lis);


      uifcComponent.ActivateDialog (techniqueviewcontroller_dialog);
      uifcComponent.DestroyDialog (techniqueviewcontroller_dialog);
    }
    catch (Throwable e) {}
  }
}
